﻿using System;
using System.Collections.Generic;
using System.Text;
using EchoFramework;
using UnityEngine;

/// <summary>
/// 存档逻辑模块
/// </summary>
public class SaveLogicModule : LogicModuleBase
{
    public static SaveLogicModule Instance
    {
        get
        {
            return LogicModuleManager.Instance.GetLogicModule<SaveLogicModule>();
        }
    }
    
    /// <summary>
    /// 关卡通关存储数据  若不存在，但又确实有关卡的，为未解锁关卡
    /// key: 关卡
    /// value: 0表示未锁定 1表示通关 -1表示锁定关卡
    /// </summary>
    private Dictionary<int, int> levelSaveDict;
    
    /// <summary>
    /// 读取存档信息
    /// </summary>
    public void ReadInfo()
    {
        if (levelSaveDict != null)
            return;
        levelSaveDict = new Dictionary<int, int>();
        string saveStr = "1,0";
        string saveData = PlayerPrefs.GetString("SaveData", saveStr);
        PlayerPrefs.SetString("SaveData", saveData.ToString());
        string[] levelArr = saveData.Split('|');
        for (int i = 0; i < levelArr.Length; i++)
        {
            string[] arr = levelArr[i].Split(',');
            int level = Convert.ToInt32(arr[0]);
            int status = Convert.ToInt32(arr[1]);
            levelSaveDict[level] = status;
        }
    }

    /// <summary>
    /// 获取关卡状态
    /// </summary>
    /// <param name="level">关卡</param>
    /// <returns>关卡状态</returns>
    public LevelStatusEnum GetLevelStatus(int level)
    {
        if (levelSaveDict.ContainsKey(level))
        {
            switch (levelSaveDict[level])
            {
                case -1: return LevelStatusEnum.Lock;
                case 0: return LevelStatusEnum.UnLock;
                case 1: return LevelStatusEnum.Pass;
            }
        }

        return LevelStatusEnum.Lock;
    }


    /// <summary>
    /// 存储数据  存储通关数据时，会默认将下一关设置为已解锁
    /// </summary>
    /// <param name="level">关卡</param>
    /// <param name="levelStatusEnum">关卡状态</param>
    public void SaveData(int level, LevelStatusEnum levelStatusEnum)
    {
        levelSaveDict[level] = (int) levelStatusEnum;
        if (levelStatusEnum == LevelStatusEnum.Pass)
        {
            if (!levelSaveDict.ContainsKey(level + 1) || levelSaveDict[level + 1] != (int) LevelStatusEnum.Pass)
                levelSaveDict[level + 1] = (int) LevelStatusEnum.UnLock;
        }

        bool isStart = true;
        StringBuilder sb = new StringBuilder();
        foreach (var singleLevelItem in levelSaveDict)
        {
            if (!isStart)
            {
                sb.Append("|");
            }

            string key = singleLevelItem.Key.ToString();
            string value = singleLevelItem.Value.ToString();
            sb.Append($"{key},{value}");
            isStart = false;
        }

        PlayerPrefs.SetString("SaveData", sb.ToString());
    }
}